package au.com.handsunited.web.aop.interceptors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.ModelAndViewDefiningException;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import au.com.handsunited.model.User;
import au.com.handsunited.model.User;
import au.com.handsunited.web.session.SessionSupport;

public class SignonInterceptor extends HandlerInterceptorAdapter {

	private static Logger logger = LoggerFactory.getLogger(SignonInterceptor.class);
	
	
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) 
			throws Exception {
		
		User user = SessionSupport.getUser(request);
		
		if (user == null) {
			String url = request.getServletPath();
			String query = request.getQueryString();
			ModelAndView modelAndView = new ModelAndView("login", "userCredentials", new User());
			
			if (query != null) {
				modelAndView.addObject("signonForwardAction", url+"?"+query);
			} else {
				modelAndView.addObject("signonForwardAction", url);
			}
			
			throw new ModelAndViewDefiningException(modelAndView);
		} else {
			return true;
		}
	}

}
